﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DSS_XNA.Engine.Error;
using DSS_XNA.Engine.Script.Variables;

namespace DSS_XNA.Engine.Script.Commands
{
    public class ScriptCommand_Subtract
    {
        #region Static Methods

        public static void Action(Dictionary<string, string> args, ScriptManager manager, Game1 engine)
        {
            if (!args.ContainsKey("target"))
                throw new DSSException("No Target parameter for Subtract");
            if (!args.ContainsKey("1"))
                throw new DSSException("No 1 parameter for Subtract");
            if (!args.ContainsKey("2"))
                throw new DSSException("No 2 parameter for Subtract");

            // ScriptManager::GetParamterValue will return the value of the passed variable
            // we want the actual variable so that we can perform this numerical
            // command, so we will check to see if the actual parameter is a variable
            // and if not, then assume it is a value

            string target = Convert.ToString(manager.GetParameterValue(args["target"]));
            string _1 = Convert.ToString(manager.GetParameterValue(args["1"]));
            string _2 = Convert.ToString(manager.GetParameterValue(args["2"]));

            IVariable targetVar = manager.GetVariable(args["target"]);
            if (targetVar == null)
                throw new DSSException(string.Format("There is no known variable with the name '{0}'",
                    args["target"]));

            IVariable var1 = manager.GetVariable(args["1"]);
            IVariable var2 = manager.GetVariable(args["2"]);

            if (var1 != null && var2 != null)
            {
                targetVar = var1.Subtract(var2);
            }
            else if (var1 == null && var2 != null)
            {
                targetVar = var2.Subtract(_1);
            }
            else if (var1 != null && var2 == null)
            {
                targetVar = var1.Subtract(_2);
            }
            else
            {
                targetVar.Value = 0; // we don't want the old value to carry on
                targetVar = targetVar.Add(_1); // we are using add here because otherwise this first operation will be (0 - _1) - which isn't correct, we want (_1 - _2) so we must first make .Value = _1 - so we add it to .Value which at this time is 0
                targetVar = targetVar.Subtract(_2);
            }

            manager.UpdateVariableValue(args["target"], targetVar.Value);
        }

        #endregion
    }
}
